import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Card, Form, Input, Button, message, Select, DatePicker } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import { RootState } from '../store';
import { updateUser } from '../store/slices/authSlice'; // 假设我们有这个action
import { updateUserProfile } from '../api/user'; // 假设我们有这个API调用

const Profile: React.FC = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const user = useSelector((state: RootState) => state.auth.user);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (user) {
      form.setFieldsValue({
        nick_name: user.nick_name,
        gender: user.gender,
        birthDay: user.birthDay ? new Date(user.birthDay).toISOString().split('T')[0] : '',
      });
    }
  }, [user, form]);

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      const updatedUser = await updateUserProfile(values);
      dispatch(updateUser(updatedUser));
      message.success('个人信息更新成功');
    } catch (error) {
      message.error('更新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  if (!user) {
    return <div>加载中...</div>;
  }

  return (
    <Card title="个人信息" style={{ maxWidth: 600, margin: '0 auto' }}>
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
      >
        <Form.Item
          name="nick_name"
          label="昵称"
          rules={[{ required: true, message: '请输入您的昵称' }]}
        >
          <Input prefix={<UserOutlined />} placeholder="昵称" />
        </Form.Item>
        <Form.Item
          name="gender"
          label="性别"
          rules={[{ required: true, message: '请选择您的性别' }]}
        >
          <Select>
            <Select.Option value="male">男性</Select.Option>
            <Select.Option value="female">女性</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="birthDay"
          label="生日"
          rules={[{ required: true, message: '请选择您的生日' }]}
        >
          <DatePicker />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            更新信息
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default Profile;
